package com.gsnd.gsnd22estore.web.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.gsnd.gsnd22estore.dto.CreateOrderDTO;
import com.gsnd.gsnd22estore.dto.OrderPayDTO;
import com.gsnd.gsnd22estore.dto.OrderPaySuccessDTO;
import com.gsnd.gsnd22estore.dto.QueryOrderDTO;
import com.gsnd.gsnd22estore.dto.extend.QueryOrderDTOExtend;
import com.gsnd.gsnd22estore.result.Result;
import com.gsnd.gsnd22estore.service.OrderService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;
    @Autowired
    private AlipayClient alipayClient;

    @GetMapping
    public Result<List<QueryOrderDTO>> getOrder(@RequestParam(required = false) String id,
                                                @RequestParam(required = false) Integer status,
                                                HttpServletRequest request){
        Integer userId = Integer.parseInt((String)request.getAttribute("userId"));
        return Result.success(orderService.getOrderByUser(userId,status,id));
    }

    @GetMapping("/{orderId}")
    public Result<QueryOrderDTOExtend> getOrderDetail(@PathVariable String orderId,
                                                      HttpServletRequest request){
        Integer userId = Integer.parseInt((String)request.getAttribute("userId"));
        return Result.success(orderService.getOrderDetailByUser(userId,orderId));
    }

    @PostMapping
    @ApiOperation("创建订单")
    public Result<QueryOrderDTOExtend> createOrder(@RequestBody CreateOrderDTO orderCreateDTO, HttpServletRequest request) {
        String userId = (String) request.getAttribute("userId");
        QueryOrderDTOExtend queryOrderDTOExtend = orderService.addOrder(orderCreateDTO, Integer.parseInt(userId));
        return Result.success(queryOrderDTOExtend);
    }

    @PutMapping("/close/{orderId}")
    @ApiOperation("关闭订单 ")
    public Result<String> closeOrder(@PathVariable("orderId") String orderId) {
        orderService.closeOrder(orderId);
        return Result.success("订单已经关闭");
    }

    @PutMapping("/paySuccess")
    public Result<String> paySuccess(@RequestBody OrderPaySuccessDTO paySuccessDTO) {
        orderService.paySuccess(paySuccessDTO);
        return Result.success("支付成功");
    }

    @PutMapping("/pay")
    @ApiOperation("支付订单")
    public Result toPayOrder(@RequestBody OrderPayDTO order) {
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        //订单支付
        model.setBody("商品描述：");
        //订单名字
        model.setSubject("杰普书城购物订单");
        //订单号
        model.setOutTradeNo(order.getOrderId());
        //过期时间
        model.setTimeoutExpress("30m");
        //订单金额
        model.setTotalAmount(order.getTotalPrice());
        //产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        //设置参数
        alipayTradePagePayRequest.setBizModel(model);
        //回调地址
        alipayTradePagePayRequest.setReturnUrl(order.getPathUrl());
        //客户端执行,拿到支付结果
        AlipayTradePagePayResponse pageExecute = null;
        try {
            pageExecute = alipayClient.pageExecute(alipayTradePagePayRequest);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        String result = pageExecute.getBody();
        return Result.success(result);
    }

    @PutMapping("/complete/{orderId}")
    @ApiOperation("确认收货")
    public Result<String > completeOrder(@PathVariable("orderId") String orderId) {
        orderService.completeOrder(orderId);
        return Result.success("确认收货");
    }
}
